package com.etc;

import org.apache.hadoop.io.NullWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Reducer;


import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class ListingReduce extends Reducer<Text,Listing,Listing, NullWritable> {
   
    @Override
    protected void reduce(Text key, Iterable<Listing> values, Context context) throws IOException, InterruptedException {
        double price = 0;
        int number = 0;
         //定义一个list集合
        List<Listing> list = new ArrayList<Listing>();
        //遍历每一条信息并添加到list集合
        for(Listing listing : values){
            //            //重新New Listing类
//            Listing listing1 = new Listing();
//            try {
//                //拷贝 Listing里面的数据
//                BeanUtils.copyProperties(listing1, listing);
//                list.add(listing1);
//            } catch (IllegalAccessException e) {
//                e.printStackTrace();
//            } catch (InvocationTargetException e) {
//                e.printStackTrace();
//            }
            price = listing.getPrice();
            number = listing.getNumber();
            list.add(new Listing(key.toString(), price, number));
        }
         //把list集合排序
        Collections.sort(list);
        for (int i = 0; i < list.size(); i++) {
            //循环输出前三条数据
            if(i == 3){
                break;
            }
            context.write(list.get(i), NullWritable.get());
        }
    }
}
